package it.univpm.diiga.memorysim.views;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import it.univpm.diiga.memorysim.data.DataPlugin;

import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Button;

public class Param extends ViewPart { 

	public static final String ID = "it.univpm.diiga.memorysim.views.Param"; 
	private IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	private String path=Platform.getLocation()+"/hdd.dat";
	private ArrayList<String> hddDim=new ArrayList<String>();
	private ArrayList<String> hddBlock=new ArrayList<String>();
	private ArrayList<String> hddTrasfer=new ArrayList<String>();
	private ArrayList<String> hddSeek=new ArrayList<String>();
	private ArrayList<String> hddRev=new ArrayList<String>();
	KeyListener moddedTxt=new KeyListener(){

		@Override
		public void keyPressed(KeyEvent e) {
			hdddata.select(hdddata.getItemCount()-1);				
		}

		@Override
		public void keyReleased(KeyEvent e) {
			// TODO Auto-generated method stub
			
		}
		
	};

	private Composite top = null;
	private Label centralmemory = null;
	private Text memorycentraldata = null;
	private Label swap = null;
	private Text swapdata = null;
	private Label block = null;
	private Text blockdata = null;
	private Label hdd = null;
	private Combo hdddata = null;
	private Group grouphdd = null;
	private Label trasferrate = null;
	private Text trasferratedata = null;
	private Label dimensionhdd = null;
	private Text hdddimensiondata = null;
	private Label seek = null;
	private Text seekdata = null;
	private Label revolutiontime = null;
	private Text revolutiontimedata = null;
	private Label blocksizehdd = null;
	private Text hdddimensionblockdata = null;
	private Button next = null;
	private Label blocksizehddlabel;
	private Label dimensionhddlabel;
	private Label trasferratelabel;
	private Label seeklabel;
	private Label revolutiontimelabel;
	private Label centralmemorylabel;
	private Label swaplabel;
	private Label blocklabel;
	
	@Override
	public void createPartControl(Composite parent) {
		harddisklogger();
		GridData gridData3 = new GridData();
		gridData3.horizontalAlignment = GridData.END;
		gridData3.verticalAlignment = GridData.CENTER;
		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.FILL;
		gridData2.grabExcessHorizontalSpace = false;
		gridData2.verticalAlignment = GridData.CENTER;
		GridLayout gridLayout = new GridLayout();
		gridLayout.verticalSpacing = 6;
		gridLayout.marginWidth = 9;
		gridLayout.marginHeight = 6;
		gridLayout.numColumns = 3;
		gridLayout.horizontalSpacing = 30;
		top = new Composite(parent, SWT.NONE);
		top.setLayout(gridLayout);
		centralmemory = new Label(top, SWT.NONE);
		centralmemory.setText("Dimensione memoria centrale");
		memorycentraldata = new Text(top, SWT.BORDER);
		centralmemorylabel = new Label(top, SWT.NONE);
		centralmemorylabel.setText("Mb");
		swap = new Label(top, SWT.NONE);
		swap.setText("Dimensione area di swap");
		swapdata = new Text(top, SWT.BORDER);
		swaplabel = new Label(top, SWT.NONE);
		swaplabel.setText("Mb");
		block = new Label(top, SWT.NONE);
		block.setText("Dimensione del blocco/frame");
		blockdata = new Text(top, SWT.BORDER);
		blocklabel = new Label(top, SWT.NONE);
		blocklabel.setText("Kb");
		hdd = new Label(top, SWT.NONE);
		hdd.setText("Seleziona il modello del disco");
		hdd.setLayoutData(gridData2);
		createHdddata();
		createGrouphdd();
		next = new Button(top, SWT.NONE);
		next.setText("Avanti");
		next.setLayoutData(gridData3);
        next.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				harddiskmod();
				try{
					DataPlugin.memorycentraldata = Integer.parseInt(memorycentraldata.getText());
					DataPlugin.swapdata = Integer.parseInt(swapdata.getText());
					DataPlugin.blockdata = Integer.parseInt(blockdata.getText());
					DataPlugin.hdddimensionblockdata = Integer.parseInt(hdddimensionblockdata.getText());
					DataPlugin.revolutiontimedata = Integer.parseInt(revolutiontimedata.getText());
					DataPlugin.hdddimensiondata = Integer.parseInt(hdddimensiondata.getText());
					DataPlugin.trasferratedata = Integer.parseInt(trasferratedata.getText());
					DataPlugin.seekdata = Integer.parseInt(seekdata.getText());					
				} catch(Exception e1){
					MessageDialog.openWarning(null, "Errore", " Errore: "+e1.getMessage());
					return;
				}
				
				if(DataPlugin.SimType==1){
				if(DataPlugin.SimSelected=="Paginazione") openPaginazione();  
				else if (DataPlugin.SimSelected=="Segmentazione") openSegmentazione();
				else if(DataPlugin.SimSelected=="Segmentazione con Paginazione") openSegWthPag();
				else MessageDialog.openInformation(null, "Vista mancante", "Non ancora implementato");
				}
				if(DataPlugin.SimType==2) openHdmanager();
				if(DataPlugin.SimType==3){
					//part of mem central
					if(DataPlugin.SimSelected=="Paginazione") openPaginazione();  
					else if (DataPlugin.SimSelected=="Segmentazione") openSegmentazione();
					else if(DataPlugin.SimSelected=="Segmentazione con Paginazione") openSegWthPag();
					else MessageDialog.openInformation(null, "Vista mancante", "Non ancora implementato");
					//part of secondary memory
					openHdmanager();
				}
			}
          });
		harddiskfinder();
		addLoadData();
	}

	private void addLoadData() {
		if(DataPlugin.memorycentraldata>0){
		memorycentraldata.setText(DataPlugin.memorycentraldata+"");
		swapdata.setText(DataPlugin.swapdata+"");
		blockdata.setText(DataPlugin.blockdata+"");
		hdddimensionblockdata.setText(DataPlugin.hdddimensionblockdata+"");
		revolutiontimedata.setText(DataPlugin.revolutiontimedata+"");
		hdddimensiondata.setText(DataPlugin.hdddimensiondata+"");
		trasferratedata.setText(DataPlugin.trasferratedata+"");
		seekdata.setText(DataPlugin.seekdata+"");
		}
	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

	/**
	 * This method initializes hdddata	
	 *
	 */
	private void createHdddata() {
		GridData gridData1 = new GridData();
		gridData1.horizontalAlignment = GridData.FILL;
		gridData1.verticalAlignment = GridData.CENTER;
		hdddata = new Combo(top, SWT.NONE);
		hdddata.setLayoutData(gridData1);
		hdddata.select(0);
		hdddata.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				
				
			}

			@Override
			public void widgetSelected(SelectionEvent e) {
				hdddimensiondata.setText(hddDim.get(hdddata.getSelectionIndex()));
				hdddimensionblockdata.setText(hddBlock.get(hdddata.getSelectionIndex()));
				trasferratedata.setText(hddTrasfer.get(hdddata.getSelectionIndex()));
				seekdata.setText(hddSeek.get(hdddata.getSelectionIndex()));
				revolutiontimedata.setText(hddRev.get(hdddata.getSelectionIndex()));
				
			}
			
		});
	}

	/**
	 * This method initializes grouphdd	
	 *
	 */
	private void createGrouphdd() {
		GridData gridData = new GridData();
		gridData.verticalAlignment = GridData.FILL;
		gridData.horizontalSpan = 2;
		gridData.grabExcessVerticalSpace = false;
		gridData.horizontalAlignment = GridData.FILL;
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.numColumns = 3;
		grouphdd = new Group(top, SWT.NONE);
		grouphdd.setText("Parametri disco");
		grouphdd.setLayoutData(gridData);
		grouphdd.setLayout(gridLayout1);
		dimensionhdd = new Label(grouphdd, SWT.NONE);
		dimensionhdd.setText("Dimensione disco");
		hdddimensiondata = new Text(grouphdd, SWT.BORDER);
		hdddimensiondata.addKeyListener(moddedTxt);
		dimensionhddlabel = new Label(grouphdd, SWT.NONE);
		dimensionhddlabel.setText("Gb");
		blocksizehdd = new Label(grouphdd, SWT.NONE);
		blocksizehdd.setText("Dimensione blocco disco");
		hdddimensionblockdata = new Text(grouphdd, SWT.BORDER);
		hdddimensionblockdata.addKeyListener(moddedTxt);
		blocksizehddlabel = new Label(grouphdd, SWT.NONE);
		blocksizehddlabel.setText("Kb");
		trasferrate = new Label(grouphdd, SWT.NONE);
		trasferrate.setText("Velocita' di trasferimento");
		trasferratedata = new Text(grouphdd, SWT.BORDER);
		trasferratedata.addKeyListener(moddedTxt);
		trasferratelabel = new Label(grouphdd, SWT.NONE);
		trasferratelabel.setText("Mbps");
		seek = new Label(grouphdd, SWT.NONE);
		seek.setText("Seek time");
		seekdata = new Text(grouphdd, SWT.BORDER);
		seekdata.addKeyListener(moddedTxt);
		seeklabel = new Label(grouphdd, SWT.NONE);
		seeklabel.setText("ms");
		revolutiontime = new Label(grouphdd, SWT.NONE);
		revolutiontime.setText("Revolution time");
		revolutiontimedata = new Text(grouphdd, SWT.BORDER);
		revolutiontimedata.addKeyListener(moddedTxt);
		revolutiontimelabel = new Label(grouphdd, SWT.NONE);
		revolutiontimelabel.setText("ms");
	}

	private void openSegmentazione(){
		try {
			 window.getActivePage().showView(Segmentazione.ID, "Segmentazione", IWorkbenchPage.VIEW_ACTIVATE);
		} catch (PartInitException e1) {
			MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e1.getMessage());
		}
	}
	
	private void openPaginazione(){
		try {
			 window.getActivePage().showView(Paginazione.ID, "Paginazione", IWorkbenchPage.VIEW_ACTIVATE);
		} catch (PartInitException e1) {
			MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e1.getMessage());
		}
	}
	
	
	private void openSegWthPag(){
		try {
			 window.getActivePage().showView(SegWthPag.ID, "Segmentazione con Paginazione", IWorkbenchPage.VIEW_ACTIVATE);
		} catch (PartInitException e1) {
			MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e1.getMessage());
		}
	}
	private void openHdmanager(){
		try {
			 window.getActivePage().showView(MemorySecondaryInitialSituation.ID, "Gestione HardDisk", IWorkbenchPage.VIEW_ACTIVATE);
		} catch (PartInitException e1) {
			MessageDialog.openError(window.getShell(), "Error", "Error opening view:" + e1.getMessage());
		}
	}
	
	private void harddisklogger(){
		try {
		    File file = new File(path);
		      if (!(file.exists())){ file.createNewFile();
		      FileOutputStream fileStream = new FileOutputStream(path);
		      PrintStream Output = new PrintStream(fileStream);

		        Output.println(DataPlugin.setDefaultHDDvalue());
		        fileStream.close();
		        }
		  }
		  catch (IOException e) {
			  MessageDialog.openError(null, "Error", "Harddisk File:"+e.getMessage()); 
		  }
	} 
	
	private void harddiskfinder() {
		try	{
			FileReader fr = new FileReader (path);
			BufferedReader inFile = new BufferedReader (fr);
			hdddata.removeAll();
			for (;;) {
				String row = inFile.readLine();
		        if (row == null) break;
		        String [] temp= row.split(",");
		        
		        hdddata.add(temp[0]);
		        hddDim.add(temp[1]);
		    	hddBlock.add(temp[2]);
		    	hddTrasfer.add(temp[3]);
		    	hddSeek.add(temp[4]);
		    	hddRev.add(temp[5]);
		        }
			inFile.close();
		hdddata.add("<Customizza Valori>");
		}
		catch (Exception exception){ MessageDialog.openError(null, "Error", "harddiskfinder: "+exception.getMessage()); }
	}
	
	public void harddisksave(){
		String stringa=	hdddata.getText()+","+hdddimensiondata.getText()+","+hdddimensionblockdata.getText()+","+
					trasferratedata.getText()+","+seekdata.getText()+","+revolutiontimedata.getText();
		try {
			FileOutputStream fos = new FileOutputStream (path, true);
			PrintWriter pw = new PrintWriter (fos);
			pw.println (stringa);
			pw.close ();
		} catch (FileNotFoundException e) {
			MessageDialog.openError(null, "Error", "Salvaggio non eseguito: "+ e.getMessage() );
		}  
		
	}
	
	public void harddiskmod(){
		boolean risp=false;
		if(hdddata.getSelectionIndex()==-1) {
			risp=MessageDialog.openConfirm(null, "Warning("+hdddata.getText()+")", "E' stato modificato un Harddisk, desideri salvarlo?");
		}
		
		if(risp){
			harddisksave();
		}
		harddiskfinder();
	}
}  